﻿@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>生产领料查询</title>
    <link href="~/scripts/layui-v2.5.6/layui/css/layui.css" rel="stylesheet" />
    <script src="~/scripts/jquery-3.4.1.min.js"></script>
    <script src="~/scripts/layui-v2.5.6/layui/layui.js"></script>
    <style>
        .search-container {
            background: #fff;
            padding: 15px;
            margin-bottom: 10px;
            border-radius: 2px;
            box-shadow: 0 1px 2px 0 rgba(0,0,0,.05);
        }
        .table-container {
            background: #fff;
            border-radius: 2px;
            box-shadow: 0 1px 2px 0 rgba(0,0,0,.05);
        }
        .search-form .layui-form-item {
            margin-bottom: 15px;
        }
        .toolbar {
            padding: 15px;
            border-bottom: 1px solid #e6e6e6;
        }
        .status-draft {
            color: #FF9800;
        }
        .status-confirmed {
            color: #4CAF50;
        }
        .status-completed {
            color: #2196F3;
        }
        .status-approving {
            color: #FFC107;
        }
        .status-approved {
            color: #8BC34A;
        }
        .status-rejected {
            color: #F44336;
        }
        .status-generated {
            color: #9C27B0;
        }
        .layui-disabled {
            background-color: #f2f2f2 !important;
            cursor: not-allowed !important;
        }
    </style>
</head>
<body>
    <div class="layui-container-fluid">
        <!-- 搜索条件区域 -->
        <div class="search-container">
            <form class="layui-form search-form" lay-filter="searchForm">
                <div class="layui-row layui-col-space15">
                    <div class="layui-col-md3">
                        <div class="layui-form-item">
                            <label class="layui-form-label">领料单编号</label>
                            <div class="layui-input-block">
                                <input type="text" name="issuanceOrderCode" placeholder="请输入领料单编号" class="layui-input">
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-md3">
                        <div class="layui-form-item">
                            <label class="layui-form-label">领料单名称</label>
                            <div class="layui-input-block">
                                <input type="text" name="issuanceOrderName" placeholder="请输入领料单名称" class="layui-input">
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-md3">
                        <div class="layui-form-item">
                            <label class="layui-form-label">仓库名称</label>
                            <div class="layui-input-block">
                                <input type="text" name="issuanceWarehouse" placeholder="请输入仓库名称" class="layui-input">
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-md3">
                        <div class="layui-form-item">
                            <label class="layui-form-label">领料日期</label>
                            <div class="layui-input-block">
                                <input type="text" name="issuanceDateRange" placeholder="开始日期 - 结束日期" class="layui-input" id="issuanceDateRange">
                            </div>
                        </div>
                    </div>
                </div>
                <div class="layui-row layui-col-space15">
                    <div class="layui-col-md3">
                        <div class="layui-form-item">
                            <label class="layui-form-label">单据状态</label>
                            <div class="layui-input-block">
                                <select name="documentStatus" lay-verify="">
                                    <option value="">请选择状态</option>
                                    <option value="草稿">草稿</option>
                                    <option value="已确认">已确认</option>
                                    <option value="审批中">审批中</option>
                                    <option value="已审批">已审批</option>
                                    <option value="已完成">已完成</option>
                                    <option value="已拒绝">已拒绝</option>
                                    <option value="生成生产工具单">生成生产工具单</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-md9" style="text-align: right;">
                        <button type="button" class="layui-btn" lay-submit lay-filter="searchBtn">
                            <i class="layui-icon layui-icon-search"></i> 搜索
                        </button>
                        <button type="reset" class="layui-btn layui-btn-primary">
                            <i class="layui-icon layui-icon-refresh"></i> 重置
                        </button>
                    </div>
                </div>
            </form>
        </div>

        <!-- 表格区域 -->
        <div class="table-container">
            <!-- 工具栏 -->
            <div class="toolbar">
                <button type="button" class="layui-btn layui-btn-sm" id="addBtn">
                    <i class="layui-icon layui-icon-add-1"></i> 新增
                </button>
                <button type="button" class="layui-btn layui-btn-sm layui-btn-normal" id="modifyBtn">
                    <i class="layui-icon layui-icon-edit"></i> 修改
                </button>
                <button type="button" class="layui-btn layui-btn-sm layui-btn-danger" id="deleteBtn">
                    <i class="layui-icon layui-icon-delete"></i> 删除
                </button>
                
                <div class="layui-btn-group" style="float: right;">
                    <button type="button" class="layui-btn layui-btn-sm layui-btn-primary" id="refreshBtn">
                        <i class="layui-icon layui-icon-refresh"></i>
                    </button>
                    <button type="button" class="layui-btn layui-btn-sm layui-btn-primary" id="settingBtn">
                        <i class="layui-icon layui-icon-set"></i>
                    </button>
                </div>
            </div>

            <!-- 数据表格 -->
            <table class="layui-hide" id="productionPickingTable" lay-filter="productionPickingTable"></table>
        </div>
    </div>

    <!-- 操作列模板 -->
    <script type="text/html" id="operationTpl">
        <a class="layui-btn layui-btn-xs layui-btn-normal" lay-event="detail">
            <i class="layui-icon layui-icon-form"></i> 执行开票
        </a>
        <a class="layui-btn layui-btn-xs" lay-event="edit">
            <i class="layui-icon layui-icon-edit"></i> 修改
        </a>
        <a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="delete">
            <i class="layui-icon layui-icon-delete"></i> 删除
        </a>
    </script>

    <!-- 单据状态模板 -->
    <script type="text/html" id="statusTpl">
        {{# if(d.documentStatus === '草稿'){ }}
            <span class="status-draft">{{ d.documentStatus }}</span>
        {{# } else if(d.documentStatus === '已确认'){ }}
            <span class="status-confirmed">{{ d.documentStatus }}</span>
        {{# } else if(d.documentStatus === '审批中'){ }}
            <span class="status-approving">{{ d.documentStatus }}</span>
        {{# } else if(d.documentStatus === '已审批'){ }}
            <span class="status-approved">{{ d.documentStatus }}</span>
        {{# } else if(d.documentStatus === '已完成'){ }}
            <span class="status-completed">{{ d.documentStatus }}</span>
        {{# } else if(d.documentStatus === '已拒绝'){ }}
            <span class="status-rejected">{{ d.documentStatus }}</span>
        {{# } else if(d.documentStatus === '生成生产工具单'){ }}
            <span class="status-generated">{{ d.documentStatus }}</span>
        {{# } else { }}
            <span class="status-draft">{{ d.documentStatus }}</span>
        {{# } }}
    </script>

    <!-- 工单选择弹窗 -->
    <div id="workOrderSelectDialog" style="display: none; padding: 20px;">
        <div class="layui-form">
            <!-- 搜索条件 -->
            <div class="layui-row layui-col-space10" style="margin-bottom: 15px;">
                <div class="layui-col-md3">
                    <input type="text" id="workOrderCode" placeholder="工单编号" class="layui-input">
                </div>
                <div class="layui-col-md3">
                    <input type="text" id="workOrderName" placeholder="工单名称" class="layui-input">
                </div>
                <div class="layui-col-md3">
                    <input type="text" id="productCode" placeholder="产品号码" class="layui-input">
                </div>
                <div class="layui-col-md3">
                    <button type="button" class="layui-btn layui-btn-sm" onclick="searchWorkOrder()">
                        <i class="layui-icon layui-icon-search"></i> 搜索
                    </button>
                    <button type="button" class="layui-btn layui-btn-sm layui-btn-primary" onclick="resetWorkOrderSearch()">
                        <i class="layui-icon layui-icon-refresh"></i> 重置
                    </button>
                </div>
            </div>
            <!-- 工单表格 -->
            <table class="layui-hide" id="workOrderTable" lay-filter="workOrderTable"></table>
        </div>
    </div>

    <!-- 生产任务选择弹窗 -->
    <div id="taskSelectDialog" style="display: none; padding: 20px;">
        <div class="layui-form">
            <!-- 搜索条件 -->
            <div class="layui-row layui-col-space10" style="margin-bottom: 15px;">
                <div class="layui-col-md3">
                    <input type="text" id="taskNumber" placeholder="任务编号" class="layui-input">
                </div>
                <div class="layui-col-md3">
                    <input type="text" id="taskWorkstationCode" placeholder="工作站编号" class="layui-input">
                </div>
                <div class="layui-col-md3">
                    <select id="taskProcessBelongs" class="layui-input">
                        <option value="">请选择工序</option>
                        <option value="印刷">印刷</option>
                        <option value="复合">复合</option>
                        <option value="分切">分切</option>
                        <option value="制袋">制袋</option>
                    </select>
                </div>
                <div class="layui-col-md3">
                    <button type="button" class="layui-btn layui-btn-sm" onclick="searchTask()">
                        <i class="layui-icon layui-icon-search"></i> 搜索
                    </button>
                    <button type="button" class="layui-btn layui-btn-sm layui-btn-primary" onclick="resetTaskSearch()">
                        <i class="layui-icon layui-icon-refresh"></i> 重置
                    </button>
                </div>
            </div>
            <!-- 任务表格 -->
            <table class="layui-hide" id="taskTable" lay-filter="taskTable"></table>
        </div>
    </div>

    <!-- 修改生产领料单弹窗 -->
    <div id="editPickingDialog" style="display: none; padding: 20px;">
        <form class="layui-form" id="editPickingForm" lay-filter="editPickingForm">
            <input type="hidden" id="editPickingId" name="id">
            
            <!-- 基本信息 -->
            <fieldset class="layui-elem-field layui-field-title">
                <legend>基本信息</legend>
            </fieldset>
            
            <div class="layui-row layui-col-space15">
                <div class="layui-col-md6">
                    <div class="layui-form-item">
                        <label class="layui-form-label"><span style="color: red;">*</span>领料单编号</label>
                        <div class="layui-input-block">
                            <input type="text" name="issuanceOrderCode" placeholder="请输入领料单编号" class="layui-input" lay-verify="required" readonly>
                        </div>
                    </div>
                </div>
                <div class="layui-col-md6">
                    <div class="layui-form-item">
                        <label class="layui-form-label"><span style="color: red;">*</span>领料单名称</label>
                        <div class="layui-input-block">
                            <input type="text" name="issuanceOrderName" placeholder="请输入领料单名称" class="layui-input" lay-verify="required">
                        </div>
                    </div>
                </div>
            </div>
            <div class="layui-row layui-col-space15">
                <div class="layui-col-md6">
                    <div class="layui-form-item">
                        <label class="layui-form-label"><span style="color: red;">*</span>领料日期</label>
                        <div class="layui-input-block">
                            <input type="text" name="issuanceDate" placeholder="请选择日期" class="layui-input" id="editIssuanceDate" lay-verify="required">
                        </div>
                    </div>
                </div>
                <div class="layui-col-md6">
                    <div class="layui-form-item">
                        <label class="layui-form-label">领料仓库</label>
                        <div class="layui-input-block">
                            <select name="issuanceWarehouse" lay-search>
                                <option value="">请选择</option>
                                <option value="原料仓">原料仓</option>
                                <option value="成品仓">成品仓</option>
                                <option value="半成品仓">半成品仓</option>
                                <option value="备件仓">备件仓</option>
                            </select>
                        </div>
                    </div>
                </div>
            </div>
            <div class="layui-row layui-col-space15">
                <div class="layui-col-md6">
                    <div class="layui-form-item">
                        <label class="layui-form-label">单据状态</label>
                        <div class="layui-input-block">
                            <select name="documentStatus">
                                <option value="草稿">草稿</option>
                                <option value="已确认">已确认</option>
                                <option value="审批中">审批中</option>
                                <option value="已审批">已审批</option>
                                <option value="已完成">已完成</option>
                                <option value="已拒绝">已拒绝</option>
                                <option value="生成生产工具单">生成生产工具单</option>
                            </select>
                        </div>
                    </div>
                </div>
                <div class="layui-col-md6">
                    <div class="layui-form-item">
                        <label class="layui-form-label"><span style="color: red;">*</span>生产工单</label>
                        <div class="layui-input-block">
                            <input type="text" name="productionWorkOrder" placeholder="生产工单" class="layui-input" lay-verify="required" readonly>
                        </div>
                    </div>
                </div>
            </div>
            <div class="layui-row layui-col-space15">
                <div class="layui-col-md6">
                    <div class="layui-form-item">
                        <label class="layui-form-label">客户编号</label>
                        <div class="layui-input-block">
                            <input type="text" name="customerCode" placeholder="请输入客户编号" class="layui-input">
                        </div>
                    </div>
                </div>
                <div class="layui-col-md6">
                    <div class="layui-form-item">
                        <label class="layui-form-label">客户名称</label>
                        <div class="layui-input-block">
                            <input type="text" name="customerName" placeholder="请输入客户名称" class="layui-input">
                        </div>
                    </div>
                </div>
            </div>
            <div class="layui-row layui-col-space15">
                <div class="layui-col-md6">
                    <div class="layui-form-item">
                        <label class="layui-form-label">生产任务</label>
                        <div class="layui-input-block">
                            <input type="text" name="productionTask" placeholder="请输入生产任务" class="layui-input">
                        </div>
                    </div>
                </div>
                <div class="layui-col-md6">
                    <div class="layui-form-item">
                        <label class="layui-form-label">任务名称</label>
                        <div class="layui-input-block">
                            <input type="text" name="taskName" placeholder="请输入任务名称" class="layui-input">
                        </div>
                    </div>
                </div>
            </div>
            <div class="layui-row layui-col-space15">
                <div class="layui-col-md6">
                    <div class="layui-form-item">
                        <label class="layui-form-label">工作站</label>
                        <div class="layui-input-block">
                            <input type="text" name="workstation" placeholder="请输入工作站" class="layui-input">
                        </div>
                    </div>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">备注</label>
                <div class="layui-input-block">
                    <textarea name="remark" placeholder="请输入备注" class="layui-textarea" rows="3"></textarea>
                </div>
            </div>

            <!-- 物料信息 -->
            <fieldset class="layui-elem-field layui-field-title">
                <legend>物料信息</legend>
            </fieldset>
            
            <!-- 物料工具栏 -->
            <div style="margin-bottom: 15px;">
                <button type="button" class="layui-btn layui-btn-sm" id="editAddMaterialBtn">
                    <i class="layui-icon layui-icon-add-1"></i> 新增
                </button>
                <button type="button" class="layui-btn layui-btn-sm layui-btn-normal" id="editEditMaterialBtn">
                    <i class="layui-icon layui-icon-edit"></i> 修改
                </button>
                <button type="button" class="layui-btn layui-btn-sm layui-btn-danger" id="editDeleteMaterialBtn">
                    <i class="layui-icon layui-icon-delete"></i> 删除
                </button>
            </div>
            
            <!-- 物料表格 -->
            <table class="layui-hide" id="editMaterialTable" lay-filter="editMaterialTable"></table>
        </form>
    </div>

    <!-- 新增生产领料单弹窗 -->
    <div id="addPickingDialog" style="display: none; padding: 20px;">
        <form class="layui-form" id="addPickingForm" lay-filter="addPickingForm">
            <div class="layui-row layui-col-space15">
                <div class="layui-col-md6">
                    <div class="layui-form-item">
                        <label class="layui-form-label"><span style="color: red;">*</span>领料单编号</label>
                        <div class="layui-input-block">
                            <div class="layui-input-inline" style="width: 200px;">
                                <input type="text" name="issuanceOrderCode" placeholder="请输入领料单编号" class="layui-input" lay-verify="required">
                            </div>
                            <div class="layui-input-inline" style="margin-left: 10px; line-height: 38px;">
                                <input type="checkbox" name="autoGenerate" lay-skin="switch" lay-text="自动生成|手动输入" lay-filter="autoGenerate">
                            </div>
                        </div>
                    </div>
                </div>
                <div class="layui-col-md6">
                    <div class="layui-form-item">
                        <label class="layui-form-label"><span style="color: red;">*</span>领料单名称</label>
                        <div class="layui-input-block">
                            <input type="text" name="issuanceOrderName" placeholder="请输入领料单名称" class="layui-input" lay-verify="required">
                        </div>
                    </div>
                </div>
            </div>
            <div class="layui-row layui-col-space15">
                <div class="layui-col-md6">
                    <div class="layui-form-item">
                        <label class="layui-form-label"><span style="color: red;">*</span>领料日期</label>
                        <div class="layui-input-block">
                            <input type="text" name="issuanceDate" placeholder="请选择日期" class="layui-input" id="issuanceDate" lay-verify="required">
                        </div>
                    </div>
                </div>
                <div class="layui-col-md6">
                    <div class="layui-form-item">
                        <label class="layui-form-label">领料仓库</label>
                        <div class="layui-input-block">
                            <select name="issuanceWarehouse" lay-search>
                                <option value="">请选择</option>
                                <option value="原料仓">原料仓</option>
                                <option value="成品仓">成品仓</option>
                                <option value="半成品仓">半成品仓</option>
                                <option value="备件仓">备件仓</option>
                            </select>
                        </div>
                    </div>
                </div>
            </div>
            <div class="layui-row layui-col-space15">
                <div class="layui-col-md6">
                    <div class="layui-form-item">
                        <label class="layui-form-label">单据状态</label>
                        <div class="layui-input-block">
                            <select name="documentStatus">
                                <option value="草稿" selected>草稿</option>
                                <option value="已确认">已确认</option>
                                <option value="审批中">审批中</option>
                                <option value="已审批">已审批</option>
                                <option value="已完成">已完成</option>
                                <option value="已拒绝">已拒绝</option>
                                <option value="生成生产工具单">生成生产工具单</option>
                            </select>
                        </div>
                    </div>
                </div>
                <div class="layui-col-md6">
                    <div class="layui-form-item">
                        <label class="layui-form-label"><span style="color: red;">*</span>生产工单</label>
                        <div class="layui-input-block">
                            <div class="layui-input-group">
                                <input type="text" name="productionWorkOrder" placeholder="请选择生产工单" class="layui-input" lay-verify="required" readonly>
                                <div class="layui-input-split layui-input-suffix" style="cursor: pointer;" id="selectWorkOrder">
                                    <i class="layui-icon layui-icon-search"></i>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="layui-row layui-col-space15">
                <div class="layui-col-md6">
                    <div class="layui-form-item">
                        <label class="layui-form-label">客户编号</label>
                        <div class="layui-input-block">
                            <input type="text" name="customerCode" placeholder="请输入客户编号" class="layui-input">
                        </div>
                    </div>
                </div>
                <div class="layui-col-md6">
                    <div class="layui-form-item">
                        <label class="layui-form-label">客户名称</label>
                        <div class="layui-input-block">
                            <input type="text" name="customerName" placeholder="请输入客户名称" class="layui-input">
                        </div>
                    </div>
                </div>
            </div>
            <div class="layui-row layui-col-space15">
                <div class="layui-col-md6">
                    <div class="layui-form-item">
                        <label class="layui-form-label">生产任务</label>
                        <div class="layui-input-block">
                            <div class="layui-input-group">
                                <input type="text" name="productionTask" placeholder="请选择生产任务" class="layui-input" readonly>
                                <div class="layui-input-split layui-input-suffix" style="cursor: pointer;" id="selectTask">
                                    <i class="layui-icon layui-icon-search"></i>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="layui-col-md6">
                    <div class="layui-form-item">
                        <label class="layui-form-label">任务名称</label>
                        <div class="layui-input-block">
                            <input type="text" name="taskName" placeholder="请输入任务名称" class="layui-input">
                        </div>
                    </div>
                </div>
            </div>
            <div class="layui-row layui-col-space15">
                <div class="layui-col-md6">
                    <div class="layui-form-item">
                        <label class="layui-form-label">工作站</label>
                        <div class="layui-input-block">
                            <input type="text" name="workstation" placeholder="请输入工作站" class="layui-input">
                        </div>
                    </div>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">备注</label>
                <div class="layui-input-block">
                    <textarea name="remark" placeholder="请输入备注" class="layui-textarea" rows="3"></textarea>
                </div>
            </div>
        </form>
    </div>

    <script>
        // 全局变量，用于在函数间共享 layui 模块
        var globalTable, globalForm, globalLaydate, globalLayer;
        var currentSearchParams = {}; // 移到全局作用域
        
        // 全局刷新表格数据函数
        function loadTableData() {
            if (globalTable) {
                // 重载表格，会自动调用url进行分页数据获取
                globalTable.reload('productionPickingTable', {
                    where: currentSearchParams
                });
            }
        }
        
        layui.use(['table', 'form', 'laydate', 'layer'], function() {
            var table = layui.table;
            var form = layui.form;
            var laydate = layui.laydate;
            var layer = layui.layer;
            
            // 设置全局变量
            globalTable = table;
            globalForm = form;
            globalLaydate = laydate;
            globalLayer = layer;

            // 初始化日期范围选择器
            laydate.render({
                elem: '#issuanceDateRange',
                range: true,
                type: 'date'
            });

            // 初始化弹窗中的日期选择器
            laydate.render({
                elem: '#issuanceDate',
                type: 'date',
                value: new Date()
            });

            // 初始化编辑弹窗的日期选择器
            laydate.render({
                elem: '#editIssuanceDate',
                type: 'date'
            });



            // 存储当前搜索条件 - 已移动到全局作用域
            // 加载表格数据函数 - 已移动到全局作用域

            // 初始化表格
            var tableIns = table.render({
                elem: '#productionPickingTable',
                url: '/Productionpicking/GetAllProductionPicking',
                method: 'GET',
                request: {
                    pageName: 'page',
                    limitName: 'limit'
                },
                parseData: function(res) {
                    // 解析返回的数据
                    console.log('原始响应数据:', res);
                    
                    if (res.success) {
                        // 转换数据格式
                        var tableData = res.data.map(function(item) {
                            return {
                                id: item.id,
                                issuanceOrderCode: item.issuanceOrderCode,
                                issuanceOrderName: item.issuanceOrderName,
                                productionWorkOrder: item.productionWorkOrder,
                                customerCode: item.customerCode || '',
                                customerName: item.customerName || '',
                                issuanceDate: item.issuanceDate ? item.issuanceDate.substring(0, 10) : '',
                                documentStatus: item.documentstatus || '草稿'
                            };
                        });
                        
                        return {
                            "code": 0,
                            "msg": res.message || "",
                            "count": res.total || 0,
                            "data": tableData
                        };
                    } else {
                        return {
                            "code": 1,
                            "msg": res.message || "数据加载失败",
                            "count": 0,
                            "data": []
                        };
                    }
                },
                cols: [[ 
                    {type: 'checkbox', fixed: 'left'},
                    {field: 'issuanceOrderCode', title: '领料单编号', width: 180, sort: true},
                    {field: 'issuanceOrderName', title: '领料单名称', width: 200},
                    {field: 'productionWorkOrder', title: '生产工单', width: 150},
                    {field: 'customerCode', title: '客户编号', width: 120},
                    {field: 'customerName', title: '客户名称', width: 150},
                    {field: 'issuanceDate', title: '领料日期', width: 120, sort: true},
                    {field: 'documentStatus', title: '单据状态', width: 120, templet: '#statusTpl'},
                    {title: '操作', width: 280, templet: '#operationTpl', fixed: 'right', align: 'center'}
                ]],
                skin: 'line',
                even: true,
                page: {
                    layout: ['count', 'prev', 'page', 'next', 'limit', 'skip'],
                    groups: 5,
                    limits: [10, 20, 50, 100],
                    curr: 1
                },
                limit: 10,
                height: 'full-150'
            });

            // 搜索功能
            form.on('submit(searchBtn)', function(data) {
                var searchData = data.field;
                
                // 更新搜索条件
                currentSearchParams = {
                    code: searchData.issuanceOrderCode || '',
                    issuanceOrderName: searchData.issuanceOrderName || '',
                    issuanceWarehouse: searchData.issuanceWarehouse || '',
                    documentStatus: searchData.documentStatus || ''
                };
                
                // 重载表格，使用新的搜索条件
                table.reload('productionPickingTable', {
                    where: currentSearchParams,
                    page: {
                        curr: 1 // 重新搜索时回到第一页
                    }
                });

                return false;
            });

            // 表格工具栏事件
            $('#addBtn').on('click', function() {
                // 重置表单
                $('#addPickingForm')[0].reset();
                form.render();
                
                // 弹出新增对话框
                layer.open({
                    type: 1,
                    title: '添加生产领料单',
                    area: ['800px', '600px'],
                    content: $('#addPickingDialog'),
                    btn: ['确定', '取消'],
                    yes: function(index, layero) {
                        // 手动验证表单
                        var formData = $('#addPickingForm').serializeArray();
                        var formObj = {};
                        $.each(formData, function(i, field) {
                            formObj[field.name] = field.value;
                        });

                        // 验证必填项
                        if (!formObj.issuanceOrderCode) {
                            layer.msg('请输入领料单编号');
                            return false;
                        }
                        if (!formObj.issuanceOrderName) {
                            layer.msg('请输入领料单名称');
                            return false;
                        }
                        if (!formObj.issuanceDate) {
                            layer.msg('请选择领料日期');
                            return false;
                        }
                        if (!formObj.productionWorkOrder) {
                            layer.msg('请选择生产工单');
                            return false;
                        }

                        // 调用后端API保存数据
                        globalLayer.load(2);
                        
                        // 构造提交数据
                        var submitData = {
                            issuanceOrderCode: formObj.issuanceOrderCode,
                            issuanceOrderName: formObj.issuanceOrderName,
                            issuanceDate: formObj.issuanceDate,
                            issuanceWarehouse: formObj.issuanceWarehouse || '',
                            productionWorkOrder: formObj.productionWorkOrder,
                            documentstatus: formObj.documentStatus || '草稿',
                            customerCode: formObj.customerCode || '',
                            customerName: formObj.customerName || '',
                            productionTask: formObj.productionTask || '',
                            taskName: formObj.taskName || '',
                            workstation: formObj.workstation || '',
                            remark: formObj.remark || ''
                        };

                        // 发送Ajax请求
                        $.ajax({
                            url: '/Productionpicking/AddProductionPicking',
                            type: 'POST',
                            contentType: 'application/json',
                            data: JSON.stringify(submitData),
                            success: function(response) {
                                layer.closeAll('loading');
                                if (response.success) {
                                    globalLayer.msg('新增成功');
                                    globalLayer.close(index);
                                    // 刷新表格数据
                                    loadTableData();
                                } else {
                                    globalLayer.msg(response.message || '保存失败');
                                }
                            },
                            error: function(xhr, status, error) {
                                globalLayer.closeAll('loading');
                                globalLayer.msg('网络错误，保存失败');
                                console.error('保存失败:', error);
                            }
                        });

                        return false;
                    },
                    btn2: function(index, layero) {
                        layer.close(index);
                    },
                    success: function(layero, index) {
                        // 重新渲染表单组件
                        form.render();
                        // 设置默认状态：开启自动生成
                        var autoGenerateSwitch = layero.find('input[name="autoGenerate"]');
                        if (autoGenerateSwitch.length > 0) {
                            autoGenerateSwitch.prop('checked', true);
                            form.render('checkbox');
                            // 触发自动生成事件
                            var today = new Date();
                            var dateStr = today.getFullYear() + 
                                         (today.getMonth() + 1).toString().padStart(2, '0') + 
                                         today.getDate().toString().padStart(2, '0');
                            var randomNum = Math.floor(Math.random() * 1000).toString().padStart(3, '0');
                            var autoCode = 'ISSUE' + dateStr + randomNum;
                            layero.find('input[name="issuanceOrderCode"]').val(autoCode).prop('readonly', true).addClass('layui-disabled');
                        }
                    }
                });
            });

            $('#modifyBtn').on('click', function() {
                var checkStatus = table.checkStatus('productionPickingTable');
                if (checkStatus.data.length === 0) {
                    layer.msg('请选择要修改的记录');
                    return;
                }
                if (checkStatus.data.length > 1) {
                    layer.msg('只能选择一条记录进行修改');
                    return;
                }
                openEditDialog(checkStatus.data[0]);
            });

            $('#deleteBtn').on('click', function() {
                var checkStatus = table.checkStatus('productionPickingTable');
                if (checkStatus.data.length === 0) {
                    layer.msg('请选择要删除的记录');
                    return;
                }
                
                var selectedData = checkStatus.data;
                var deleteIds = selectedData.map(function(item) {
                    return item.id;
                });
                
                var confirmText = selectedData.length === 1 
                    ? '您确定要删除领料单 "' + selectedData[0].issuanceOrderCode + '" 吗？'
                    : '您确定要删除选中的 ' + selectedData.length + ' 条记录吗？';
                
                layer.confirm(confirmText, {
                    icon: 3,
                    title: '删除确认'
                }, function(confirmIndex) {
                    // 关闭确认对话框
                    layer.close(confirmIndex);
                    
                    // 显示加载层
                    var loadingIndex = globalLayer.load(2, {
                        shade: [0.3, '#000']
                    });

                    // 批量删除
                    var deletePromises = deleteIds.map(function(id) {
                        return $.ajax({
                            url: '/Productionpicking/DeleteProductionPicking',
                            type: 'POST',
                            data: { id: id }
                        });
                    });

                    // 等待所有删除操作完成
                    Promise.all(deletePromises).then(function(responses) {
                        globalLayer.close(loadingIndex);
                        
                        var successCount = 0;
                        var failCount = 0;
                        
                        responses.forEach(function(response) {
                            if (response.success) {
                                successCount++;
                            } else {
                                failCount++;
                            }
                        });
                        
                        if (failCount === 0) {
                            globalLayer.msg('删除成功，共删除 ' + successCount + ' 条记录', {
                                icon: 1,
                                time: 2000
                            });
                        } else {
                            globalLayer.msg('删除完成，成功 ' + successCount + ' 条，失败 ' + failCount + ' 条', {
                                icon: 0,
                                time: 3000
                            });
                        }
                        
                        // 刷新表格
                        loadTableData();
                        
                    }).catch(function(error) {
                        globalLayer.close(loadingIndex);
                        globalLayer.msg('删除失败：网络错误', {
                            icon: 2,
                            time: 3000
                        });
                        console.error('删除失败:', error);
                    });
                });
            });

            $('#refreshBtn').on('click', function() {
                loadTableData();
                globalLayer.msg('刷新成功');
            });



            // 行工具事件
            table.on('tool(productionPickingTable)', function(obj) {
                var data = obj.data;
                if (obj.event === 'detail') {
                    // 执行开票
                    executeInvoice(data);
                } else if (obj.event === 'edit') {
                    openEditDialog(data);
                } else if (obj.event === 'delete') {
                    deleteProductionPicking(data);
                }
            });

            // 重置表单
            $('button[type="reset"]').on('click', function() {
                $('.search-form')[0].reset();
                form.render('select'); // 重新渲染下拉框
                
                // 清空搜索条件
                currentSearchParams = {};
                
                // 重载表格，回到默认状态
                table.reload('productionPickingTable', {
                    where: {},
                    page: {
                        curr: 1
                    }
                });
            });

            // 自动生成编号开关事件
            form.on('switch(autoGenerate)', function(data) {
                var codeInput = $('input[name="issuanceOrderCode"]');
                if (data.elem.checked) {
                    // 生成自动编号
                    var today = new Date();
                    var dateStr = today.getFullYear() + 
                                 (today.getMonth() + 1).toString().padStart(2, '0') + 
                                 today.getDate().toString().padStart(2, '0');
                    var randomNum = Math.floor(Math.random() * 1000).toString().padStart(3, '0');
                    var autoCode = 'ISSUE' + dateStr + randomNum;
                    codeInput.val(autoCode).prop('readonly', true).addClass('layui-disabled');
                } else {
                    codeInput.val('').prop('readonly', false).removeClass('layui-disabled');
                }
            });

            // 生产工单选择事件
            $(document).on('click', '#selectWorkOrder', function() {
                showWorkOrderSelectDialog();
            });

            // 生产任务选择事件
            $(document).on('click', '#selectTask', function() {
                showTaskSelectDialog();
            });


        });

        // 显示工单选择弹窗
        function showWorkOrderSelectDialog() {
            console.log('开始打开工单选择弹窗...');
            
            var workOrderDialog = layer.open({
                type: 1,
                title: '工单选择',
                area: ['1200px', '600px'],
                content: $('#workOrderSelectDialog'),
                btn: ['确定', '取消'],
                yes: function(index, layero) {
                    var selectedData = globalTable.checkStatus('workOrderTable').data;
                    console.log('确定按钮被点击，选中的数据:', selectedData);
                    
                    if (selectedData.length === 0) {
                        globalLayer.msg('请选择一个工单');
                        return false;
                    }
                    if (selectedData.length > 1) {
                        globalLayer.msg('只能选择一个工单');
                        return false;
                    }
                    
                    // 填充工单信息到表单
                    var workOrder = selectedData[0];
                    $('input[name="productionWorkOrder"]').val(workOrder.workOrderCode);
                    // 同时填充客户信息（如果有的话）
                    if (workOrder.customerCode) {
                        $('input[name="customerCode"]').val(workOrder.customerCode);
                    }
                    if (workOrder.customerName) {
                        $('input[name="customerName"]').val(workOrder.customerName);
                    }
                    
                    console.log('选择的工单信息:', workOrder);
                    
                    globalLayer.close(index);
                },
                btn2: function(index, layero) {
                    globalLayer.close(index);
                },
                success: function(layero, index) {
                    console.log('弹窗打开成功，开始初始化表格...');
                    // 初始化工单选择表格
                    initWorkOrderTable();
                    // 立即加载工单数据
                    setTimeout(function() {
                        console.log('延迟执行，开始加载工单数据...');
                        loadWorkOrderData();
                    }, 500); // 增加延迟时间
                }
            });
        }

        // 初始化工单选择表格
        function initWorkOrderTable() {
            if (window.workOrderTableIns) {
                return; // 避免重复初始化
            }
            
            window.workOrderTableIns = globalTable.render({
                elem: '#workOrderTable',
                id: 'workOrderTable',
                data: [],
                cols: [[ 
                    {type: 'radio', fixed: 'left'},
                    {field: 'workOrderCode', title: '工单编号', width: 150},
                    {field: 'workOrderName', title: '工单名称', width: 150},
                    {field: 'sourceType', title: '工单来源', width: 100},
                    {field: 'orderCode', title: '订单号码', width: 120},
                    {field: 'productCode', title: '产品号码', width: 120},
                    {field: 'productName', title: '产品名称', width: 150},
                    {field: 'productModel', title: '规格型号', width: 100},
                    {field: 'unit', title: '单位', width: 80},
                    {field: 'workOrderQuantity', title: '工单数量', width: 100},
                    {field: 'customerCode', title: '客户编号', width: 100},
                    {field: 'customerName', title: '客户名称', width: 120},
                    {field: 'demandDate', title: '需求日期', width: 120, templet: function(d) {
                        if (d.demandDate) {
                            var date = new Date(d.demandDate);
                            return date.getFullYear() + '-' + 
                                   (date.getMonth() + 1).toString().padStart(2, '0') + '-' + 
                                   date.getDate().toString().padStart(2, '0');
                        }
                        return '';
                    }}
                ]],
                skin: 'line',
                even: true,
                page: {
                    layout: ['count', 'prev', 'page', 'next', 'limit'],
                    groups: 5,
                    limits: [10, 20, 50],
                    curr: 1
                },
                limit: 10,
                height: 400,
                text: {
                    none: '暂无数据'
                }
            });
        }

        // 加载工单数据
        function loadWorkOrderData(searchParams = {}) {
            console.log('开始加载工单数据...', searchParams);
            $.ajax({
                url: '/ProductionWorkOrderMain/GetProductionWorkOrderList',
                type: 'GET',
                data: {
                    workOrderCode: searchParams.workOrderCode || '',
                    workOrderName: searchParams.workOrderName || '',
                    productCode: searchParams.productCode || ''
                },
                success: function(response) {
                    console.log('工单数据响应:', response);
                    if (response.code === 0) {
                        console.log('工单数据加载成功，条数:', response.data ? response.data.length : 0);
                        // 重新渲染表格
                        globalTable.reload('workOrderTable', {
                            data: response.data || []
                        });
                        
                        if (!response.data || response.data.length === 0) {
                            globalLayer.msg('暂无工单数据');
                        }
                    } else {
                        globalLayer.msg('加载工单数据失败：' + (response.msg || '未知错误'));
                        console.error('API返回错误:', response);
                    }
                },
                error: function(xhr, status, error) {
                    globalLayer.msg('网络错误，加载工单数据失败');
                    console.error('加载工单数据失败:', {xhr: xhr, status: status, error: error});
                }
            });
        }

        // 工单搜索
        function searchWorkOrder() {
            var searchParams = {
                workOrderCode: $('#workOrderCode').val(),
                workOrderName: $('#workOrderName').val(),
                productCode: $('#productCode').val()
            };
            loadWorkOrderData(searchParams);
        }

        // 重置工单搜索
        function resetWorkOrderSearch() {
            $('#workOrderCode').val('');
            $('#workOrderName').val('');
            $('#productCode').val('');
            loadWorkOrderData();
        }

        // 显示生产任务选择弹窗
        function showTaskSelectDialog() {
            console.log('开始打开任务选择弹窗...');
            
            var taskDialog = globalLayer.open({
                type: 1,
                title: '任务选择',
                area: ['1200px', '600px'],
                content: $('#taskSelectDialog'),
                btn: ['确定', '取消'],
                yes: function(index, layero) {
                    var selectedData = globalTable.checkStatus('taskTable').data;
                    console.log('确定按钮被点击，选中的任务数据:', selectedData);
                    
                    if (selectedData.length === 0) {
                        globalLayer.msg('请选择一个任务');
                        return false;
                    }
                    if (selectedData.length > 1) {
                        globalLayer.msg('只能选择一个任务');
                        return false;
                    }
                    
                    // 填充任务信息到表单
                    var task = selectedData[0];
                    $('input[name="productionTask"]').val(task.taskNumber);
                    $('input[name="taskName"]').val(task.taskName);
                    $('input[name="workstation"]').val(task.workstationName);
                    
                    console.log('选择的任务信息:', task);
                    
                    globalLayer.close(index);
                },
                btn2: function(index, layero) {
                    globalLayer.close(index);
                },
                success: function(layero, index) {
                    console.log('任务弹窗打开成功，开始初始化表格...');
                    // 初始化任务选择表格
                    initTaskTable();
                    // 立即加载任务数据
                    setTimeout(function() {
                        console.log('延迟执行，开始加载任务数据...');
                        loadTaskData();
                    }, 500);
                }
            });
        }

        // 初始化生产任务选择表格
        function initTaskTable() {
            if (window.taskTableIns) {
                return; // 避免重复初始化
            }
            
            window.taskTableIns = globalTable.render({
                elem: '#taskTable',
                id: 'taskTable',
                data: [],
                cols: [[ 
                    {type: 'radio', fixed: 'left'},
                    {field: 'taskNumber', title: '任务编号', width: 150},
                    {field: 'taskName', title: '任务名称', width: 180},
                    {field: 'workstationCode', title: '工作站编号', width: 120},
                    {field: 'workstationName', title: '工作站名称', width: 150},
                    {field: 'processBelongs', title: '所属工序', width: 100},
                    {field: 'schedulingNumber', title: '排产数量', width: 100},
                    {field: 'producedNumber', title: '已生产数量', width: 100},
                    {field: 'startProducedTime', title: '开始生产时间', width: 160, templet: function(d) {
                        if (d.startProducedTime) {
                            var date = new Date(d.startProducedTime);
                            return date.getFullYear() + '-' + 
                                   (date.getMonth() + 1).toString().padStart(2, '0') + '-' + 
                                   date.getDate().toString().padStart(2, '0') + ' ' +
                                   date.getHours().toString().padStart(2, '0') + ':' +
                                   date.getMinutes().toString().padStart(2, '0');
                        }
                        return '';
                    }},
                    {field: 'producedDuration', title: '生产时长', width: 100},
                    {field: 'estimatedCompletionTime', title: '预计完成时间', width: 160, templet: function(d) {
                        if (d.estimatedCompletionTime) {
                            var date = new Date(d.estimatedCompletionTime);
                            return date.getFullYear() + '-' + 
                                   (date.getMonth() + 1).toString().padStart(2, '0') + '-' + 
                                   date.getDate().toString().padStart(2, '0') + ' ' +
                                   date.getHours().toString().padStart(2, '0') + ':' +
                                   date.getMinutes().toString().padStart(2, '0');
                        }
                        return '';
                    }}
                ]],
                skin: 'line',
                even: true,
                page: {
                    layout: ['count', 'prev', 'page', 'next', 'limit'],
                    groups: 5,
                    limits: [10, 20, 50],
                    curr: 1
                },
                limit: 10,
                height: 400,
                text: {
                    none: '暂无数据'
                }
            });
        }

        // 加载生产任务数据
        function loadTaskData(searchParams = {}) {
            console.log('开始加载任务数据...', searchParams);
            $.ajax({
                url: '/ProductionReport/GetProductionTask',
                type: 'GET',
                data: {
                    processBelongs: searchParams.processBelongs || '',
                    workstationCode: searchParams.workstationCode || '',
                    taskNumber: searchParams.taskNumber || ''
                },
                success: function(response) {
                    console.log('任务数据响应:', response);
                    // 直接使用返回的数组，因为这个接口返回的是List<ProductionTask>
                    if (Array.isArray(response)) {
                        console.log('任务数据加载成功，条数:', response.length);
                        // 重新渲染表格
                        globalTable.reload('taskTable', {
                            data: response
                        });
                        
                        if (response.length === 0) {
                            globalLayer.msg('暂无任务数据');
                        }
                    } else {
                        globalLayer.msg('任务数据格式错误');
                        console.error('API返回格式错误:', response);
                    }
                },
                error: function(xhr, status, error) {
                    globalLayer.msg('网络错误，加载任务数据失败');
                    console.error('加载任务数据失败:', {xhr: xhr, status: status, error: error});
                }
            });
        }

        // 任务搜索
        function searchTask() {
            var searchParams = {
                taskNumber: $('#taskNumber').val(),
                workstationCode: $('#taskWorkstationCode').val(),
                processBelongs: $('#taskProcessBelongs').val()
            };
            loadTaskData(searchParams);
        }

        // 重置任务搜索
        function resetTaskSearch() {
            $('#taskNumber').val('');
            $('#taskWorkstationCode').val('');
            $('#taskProcessBelongs').val('');
            loadTaskData();
        }

        // 全局函数：选择工单
        function selectWorkOrderItem(workOrderCode) {
            $('input[name="productionWorkOrder"]').val(workOrderCode);
            layer.closeAll('page');
        }

        // 全局函数：选择任务
        function selectTaskItem(taskCode) {
            $('input[name="productionTask"]').val(taskCode);
            layer.closeAll('page');
        }

        // 打开修改弹窗
        var editMaterialData = []; // 存储编辑时的物料数据
        function openEditDialog(data) {
            // 重置表单
            $('#editPickingForm')[0].reset();
            globalForm.render();
            
            // 显示加载层
            var loadingIndex = globalLayer.load(2, {
                shade: [0.3, '#000']
            });

            // 调用API获取详细数据
            $.ajax({
                url: '/Productionpicking/GetProductionPickingById',
                type: 'GET',
                data: { id: data.id },
                success: function(response) {
                    globalLayer.close(loadingIndex);
                    if (response.success && response.data) {
                        var detailData = response.data;
                        
                        // 填充基本数据
                        $('#editPickingId').val(detailData.id);
                        $('#editPickingForm input[name="issuanceOrderCode"]').val(detailData.issuanceOrderCode);
                        $('#editPickingForm input[name="issuanceOrderName"]').val(detailData.issuanceOrderName);
                        $('#editPickingForm input[name="issuanceDate"]').val(detailData.issuanceDate ? detailData.issuanceDate.substring(0, 10) : '');
                        $('#editPickingForm select[name="issuanceWarehouse"]').val(detailData.issuanceWarehouse || '');
                        $('#editPickingForm select[name="documentStatus"]').val(detailData.documentstatus || '');
                        $('#editPickingForm input[name="productionWorkOrder"]').val(detailData.productionWorkOrder || '');
                        $('#editPickingForm input[name="customerCode"]').val(detailData.customerCode || '');
                        $('#editPickingForm input[name="customerName"]').val(detailData.customerName || '');
                        $('#editPickingForm input[name="productionTask"]').val(detailData.productionTask || '');
                        $('#editPickingForm input[name="taskName"]').val(detailData.taskName || '');
                        $('#editPickingForm input[name="workstation"]').val(detailData.workstation || '');
                        $('#editPickingForm textarea[name="remark"]').val(detailData.remark || '');
                        
                        // 重新渲染表单组件
                        globalForm.render();
                        
                        // 模拟物料数据（后续可以从API获取）
                        editMaterialData = [
                            {
                                id: 1,
                                productCode: 'YCL00010',
                                productName: 'ET',
                                specifications: '20*20*20',
                                unit: 'm',
                                quantity: 1,
                                batch: '预置仓库',
                                warehouse: '预置库区',
                                storageLocation: '预置库位'
                            },
                            {
                                id: 2,
                                productCode: 'YCL00011',
                                productName: 'PP',
                                specifications: '50*50*50',
                                unit: 'm',
                                quantity: 2,
                                batch: '预置仓库',
                                warehouse: '预置库区',
                                storageLocation: '预置库位'
                            }
                        ];
                        
                        // 初始化物料表格
                        initEditMaterialTable();
                        
                        // 数据加载完成后，弹出编辑对话框
                        showEditDialog();
                        
                    } else {
                        globalLayer.msg('获取数据失败：' + (response.message || '未知错误'), {
                            icon: 2,
                            time: 3000
                        });
                    }
                },
                error: function(xhr, status, error) {
                    globalLayer.close(loadingIndex);
                    globalLayer.msg('网络错误，获取数据失败', {
                        icon: 2,
                        time: 3000
                    });
                    console.error('获取详细数据失败:', error);
                }
            });
        }

        // 显示编辑对话框
        function showEditDialog() {
            globalLayer.open({
                type: 1,
                title: '修改生产领料单',
                area: ['90%', '90%'],
                content: $('#editPickingDialog'),
                btn: ['确定', '取消'],
                yes: function(index, layero) {
                    // 获取表单数据
                    var formData = $('#editPickingForm').serializeArray();
                    var formObj = {};
                    $.each(formData, function(i, field) {
                        formObj[field.name] = field.value;
                    });

                    // 验证必填项
                    if (!formObj.issuanceOrderCode) {
                        globalLayer.msg('请输入领料单编号');
                        return false;
                    }
                    if (!formObj.issuanceOrderName) {
                        globalLayer.msg('请输入领料单名称');
                        return false;
                    }
                    if (!formObj.issuanceDate) {
                        globalLayer.msg('请选择领料日期');
                        return false;
                    }
                    if (!formObj.productionWorkOrder) {
                        globalLayer.msg('请选择生产工单');
                        return false;
                    }

                    // 获取ID值
                    var editId = $('#editPickingId').val();
                    console.log('编辑ID:', editId);
                    
                    // 验证ID
                    if (!editId || editId === '' || parseInt(editId) <= 0) {
                        globalLayer.msg('无效的记录ID');
                        return false;
                    }

                    // 构造提交数据
                    var submitData = {
                        id: parseInt(editId),
                        issuanceOrderCode: formObj.issuanceOrderCode,
                        issuanceOrderName: formObj.issuanceOrderName,
                        issuanceDate: formObj.issuanceDate,
                        issuanceWarehouse: formObj.issuanceWarehouse || '',
                        productionWorkOrder: formObj.productionWorkOrder,
                        documentstatus: formObj.documentStatus || '草稿',
                        customerCode: formObj.customerCode || '',
                        customerName: formObj.customerName || '',
                        productionTask: formObj.productionTask || '',
                        taskName: formObj.taskName || '',
                        workstation: formObj.workstation || '',
                        remark: formObj.remark || ''
                    };

                    // 显示加载层
                    var loadingIndex = globalLayer.load(2, {
                        shade: [0.3, '#000']
                    });

                    // 添加调试信息
                    console.log('提交的数据:', submitData);
                    
                    // 调用后端API修改数据
                    $.ajax({
                        url: '/Productionpicking/UpdateProductionPicking',
                        type: 'POST',
                        contentType: 'application/json',
                        data: JSON.stringify(submitData),
                        success: function(response) {
                            console.log('API响应:', response);
                            globalLayer.close(loadingIndex);
                            if (response.success) {
                                globalLayer.msg(response.message || '修改成功', {
                                    icon: 1,
                                    time: 2000
                                });
                                globalLayer.close(index);
                                // 刷新表格数据
                                loadTableData();
                            } else {
                                globalLayer.msg(response.message || '修改失败', {
                                    icon: 2,
                                    time: 3000
                                });
                            }
                        },
                        error: function(xhr, status, error) {
                            globalLayer.close(loadingIndex);
                            console.error('AJAX错误详情:', {
                                status: xhr.status,
                                statusText: xhr.statusText,
                                responseText: xhr.responseText,
                                error: error
                            });
                            
                            var errorMsg = '网络错误，修改失败';
                            if (xhr.responseText) {
                                try {
                                    var errorResponse = JSON.parse(xhr.responseText);
                                    errorMsg = errorResponse.message || errorMsg;
                                } catch (e) {
                                    errorMsg += ' (状态码: ' + xhr.status + ')';
                                }
                            }
                            
                            globalLayer.msg(errorMsg, {
                                icon: 2,
                                time: 5000
                            });
                        }
                    });

                    return false;
                },
                btn2: function(index, layero) {
                    globalLayer.close(index);
                },
                success: function(layero, index) {
                    // 重新渲染表单组件
                    globalForm.render();
                }
            });
        }

        // 初始化编辑物料表格
        function initEditMaterialTable() {
            globalTable.render({
                elem: '#editMaterialTable',
                data: editMaterialData,
                cols: [[ 
                    {type: 'checkbox', fixed: 'left'},
                    {field: 'productCode', title: '产品物料编号', width: 150},
                    {field: 'productName', title: '产品物料名称', width: 200},
                    {field: 'specifications', title: '规格型号', width: 120},
                    {field: 'unit', title: '单位', width: 80},
                    {field: 'quantity', title: '领料数量', width: 100, edit: 'text'},
                    {field: 'batch', title: '批次号', width: 120},
                    {field: 'warehouse', title: '仓库名称', width: 120},
                    {field: 'storageLocation', title: '库位名称', width: 120}
                ]],
                skin: 'line',
                even: true,
                page: false,
                height: 300
            });
        }

        // 执行开票
        function executeInvoice(data) {
            // 检查单据状态
            if (data.documentStatus === '已完成') {
                globalLayer.msg('该领料单已完成开票', {icon: 0});
                return;
            }

            // 确认执行开票
            globalLayer.confirm('确定要对领料单 "' + data.issuanceOrderCode + '" 执行开票吗？<br>执行后单据状态将变更为已完成。', {
                icon: 3,
                title: '确认开票'
            }, function(confirmIndex) {
                // 关闭确认对话框
                globalLayer.close(confirmIndex);
                
                // 显示加载层
                var loadingIndex = globalLayer.load(2, {
                    shade: [0.3, '#000']
                });

                // 调用后端API执行开票
                $.ajax({
                    url: '/Productionpicking/ExecuteInvoice',
                    type: 'POST',
                    data: {
                        id: data.id
                    },
                    success: function(response) {
                        globalLayer.close(loadingIndex);
                        if (response.success) {
                            globalLayer.msg(response.message || '开票成功', {
                                icon: 1,
                                time: 2000
                            });
                            // 立即刷新表格数据
                            loadTableData();
                        } else {
                            globalLayer.msg(response.message || '开票失败', {
                                icon: 2,
                                time: 3000
                            });
                        }
                    },
                    error: function(xhr, status, error) {
                        globalLayer.close(loadingIndex);
                        globalLayer.msg('网络错误，开票失败', {
                            icon: 2,
                            time: 3000
                        });
                        console.error('开票失败:', error);
                    }
                });
            });
        }

        // 删除生产领料单
        function deleteProductionPicking(data) {
            // 确认删除
            globalLayer.confirm('您确定要删除领料单 "' + data.issuanceOrderCode + '" 吗？', {
                icon: 3,
                title: '删除确认'
            }, function(confirmIndex) {
                // 关闭确认对话框
                globalLayer.close(confirmIndex);
                
                // 显示加载层
                var loadingIndex = globalLayer.load(2, {
                    shade: [0.3, '#000']
                });

                // 调用后端API删除数据
                $.ajax({
                    url: '/Productionpicking/DeleteProductionPicking',
                    type: 'POST',
                    data: {
                        id: data.id
                    },
                    success: function(response) {
                        globalLayer.close(loadingIndex);
                        if (response.success) {
                            globalLayer.msg(response.message || '删除成功', {
                                icon: 1,
                                time: 2000
                            });
                            // 刷新表格数据
                            loadTableData();
                        } else {
                            globalLayer.msg(response.message || '删除失败', {
                                icon: 2,
                                time: 3000
                            });
                        }
                    },
                    error: function(xhr, status, error) {
                        globalLayer.close(loadingIndex);
                        globalLayer.msg('网络错误，删除失败', {
                            icon: 2,
                            time: 3000
                        });
                        console.error('删除失败:', error);
                    }
                });
            }, function(cancelIndex) {
                // 点击取消按钮
                globalLayer.close(cancelIndex);
            });
        }
    </script>
</body>
</html>

